package com.alks.function.controller.pcFactoryQuery;

import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.Idempotent;
import com.alks.common.aop.RoleCheck;
import com.alks.common.aop.WebLogger;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.request.factoryquery.StitchHeadRequest;
import com.alks.function.data.vo.pcfactoryWork.DailyExportVo;
import com.alks.function.data.vo.stock.StitchStkFlowVo;
import com.alks.function.service.async.FileExportAsyncService;
import com.alks.function.service.pcfactoryquery.IPcStitchDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@ApiRestController("/pcFactorQuery")
@Api(value = "总经办", tags = "总经办-工厂查询模块-鞋面库存查询")
@Slf4j
@RoleCheck(prgIds = {"100418", "140210", "160216", "110310", "180716", "190215", "170515"})
public class StitchStkController {
    @Autowired
    private IPcStitchDetailService stitchService;
    @Autowired
    private FileExportAsyncService exportService;

    @PutMapping("/queryStitchDeptHead")
    @ApiOperation(value = "鞋面库存-鞋面仓库账目-条件查询", tags = "总经办-工厂查询模块-鞋面库存查询")
    @WebLogger
    public ResponseInfo queryStitchDeptHead(@RequestBody StitchHeadRequest request) {
        return stitchService.queryStitchDeptHead(request);
    }

    @GetMapping("/queryStitchDeptDetail")
    @ApiOperation(value = "鞋面库存-鞋面仓库部门明细-条件查询", tags = "总经办-工厂查询模块-鞋面库存查询")
    @WebLogger
    public ResponseInfo queryStitchDeptDetail(@RequestParam(value = "deptName", required = false) String deptName,
                                              @RequestParam(value = "slipType", required = false) String slipType) {
        return stitchService.queryStitchDeptDetail(deptName, slipType);
    }


    @PutMapping("/stitchStkDayExport")
    @ApiOperation(value = "日报表导出-导出EXCEL", tags = "总经办-工厂查询模块-鞋面库存查询")
    @WebLogger
    public void stitchStkDayExport(@RequestBody StitchHeadRequest request,
                                   HttpServletResponse response) {
        /*数据初始化*/
        request.setPageSize(-1);
        request.setExportDate(request.getExportDate()==null? LocalDate.now().atStartOfDay().minusDays(1):request.getExportDate());
        String templet = "鞋面仓库日报表模版.xls";
        String fileName = "鞋面仓日报表" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + ".xls";
        /*获取数据*/
        List<DailyExportVo> exportList = stitchService.dailyExportDateQuery(request);
        try {
            Map<String, Object> map = new HashMap<>(1);
            map.put("date",request.getExportDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            ExcelUtils.autoWidth(1).creatByTemplate(response, templet, fileName, exportList,map);
        } catch (Exception e) {
            log.error("\n错误接口：stitchStkDayExport\n错误原因：",e);
            throw new ServiceErrorException("导出失败");
        }
    }

    @PostMapping("/stitchStk/sizeExport")
    @ApiOperation(value = "导出面仓台账（号码）-导出EXCEL", tags = "总经办-工厂查询模块-鞋面库存查询")
    @WebLogger
    @Idempotent(expireTime = 10)
    public ResponseInfo stitchStkSizeExport(@RequestBody StitchHeadRequest request) {
        //MS TODO 2025/1/16 : 放到下载列表
        request.setExportDate(request.getExportDate()==null? LocalDate.now().atStartOfDay().minusDays(1):request.getExportDate());
        exportService.doStitchStkExport(request, UserIdThread.get());
        return ResponseInfo.fileLoading();
    }

    @PostMapping("/export/stitchStkFlow")
    @ApiOperation(value = "导出收发料报表-导出EXCEL", tags = "总经办-工厂查询模块-鞋面库存查询")
    @WebLogger
    public void stitchStkFlowExport(@RequestBody StitchHeadRequest request,HttpServletResponse response) {
        if (request.getSlipDateStart()==null||request.getSlipDateEnd()==null) {
            throw new ServiceErrorException("请选择时间范围");
        }
        List<StitchStkFlowVo> voList = stitchService.stitchStkFlowExport(request);
        try {
            String templateName = "鞋面仓库收发料报表模版.xls";
            String excelName = "鞋面仓库收发料报表" + DateUtils.dateTimeNow() + ".xls";
            Map<String,Object> map = new HashMap<>(3);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String exportDate = request.getSlipDateStart().format(formatter) + "至" + request.getSlipDateEnd().format(formatter);
            map.put("exportDate", exportDate);
            if (ArrayUtils.isNoEmpyt(voList)){
                BigDecimal inQtySum = voList.stream().map(StitchStkFlowVo::getInQty).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal outQtySum = voList.stream().map(StitchStkFlowVo::getOutQty).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                map.put("inQtySum",inQtySum);
                map.put("outQtySum",outQtySum);
            }
            ExcelUtils.autoWidth(3).creatByTemplate(response, templateName, excelName, voList,map);
        } catch (IOException e) {
            log.error("\n错误接口：stitchStkFlowExport\n错误原因：",e);
            throw new ServiceErrorException("导出失败");
        }
    }


}
